import time
from selenium import webdriver
import pymysql
db = pymysql.connect("localhost", "root", "123", "phone")
cursor = db.cursor()
chromedriver = "D:\Python\chromedriver.exe"
try:
    browser = webdriver.Chrome(chromedriver)
    browser.get('https://mail.qq.com/cgi-bin/loginpage')
    browser.switch_to.frame('login_frame')
    #表单提交
    # browser.find_element_by_name('u').send_keys('qq账号')
    # time.sleep(3)
    # browser.find_element_by_name('p').send_keys('qq密码')
    # time.sleep(3)
    # browser.find_element_by_class_name('login_button').click()
    browser.find_element_by_id("img_out_1874751031").click()

    time.sleep(3)
    # browser.switch_to.window(browser.window_handles[-1])
    browser.switch_to.frame("mainFrame")
    browser.find_element_by_name("folder_unread").click()
    time.sleep(3)

    a = browser.find_element_by_id("div_showtoday")
    b = a.find_elements_by_class_name("l")

    count = 0
    for i in b:
        try:
            msg = b[count].find_element_by_class_name("gt")
            if msg.text[0:11] == "来自qq.com的退信":
                msg.click()
            body = browser.find_element_by_id("mailContentContainer").text
            body = body.replace("\n", "").replace(" ", "")
            body = body.split("无法发送到")
            body = body[1].split("退信原因")
            email = body[0]

            sql = "INSERT INTO `badman_and_carelessman`(username) values('%s')" %email
            cursor.execute(sql)
            db.commit()
            browser.back()

            time.sleep(1)
            browser.switch_to.frame("mainFrame")
            a = browser.find_element_by_id("div_showtoday")
            b = a.find_elements_by_class_name("l")
        except Exception as e:
            print(e)

        count += 1


    sqll = "SELECT username from badman_and_carelessman WHERE badman_and_carelessman.username in (SELECT u_email from phones_user);"
    cursor.execute(sqll)
    data = cursor.fetchall()
    for i in data:
        sqlll = "delete from phones_user where u_email = '%s'" %(i[0])
        print(sqlll)
        cursor.execute(sqlll)
        db.commit()

# sqllll = "TRUNCATE badman_and_carelessman"      #删除无效用户表操作
# cursor.execute(sqllll)
# db.commit()

    browser.quit()
except Exception as e:
    print(e)


